package com.wtx.fitness.controller;

import com.wtx.fitness.common.Result;
import com.wtx.fitness.common.ResultCode;
import com.wtx.fitness.entity.Announcement;
import com.wtx.fitness.exception.BusinessException;
import com.wtx.fitness.exception.NotFoundException;
import com.wtx.fitness.exception.UnauthorizedException;
import com.wtx.fitness.service.AnnouncementService;
import com.wtx.fitness.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公告控制器
 */
@RestController
@RequestMapping("/api")
public class AnnouncementController {

  @Autowired
  private AnnouncementService announcementService;

  /**
   * 获取公告列表
   */
  @GetMapping("/announcements")
  public Result<List<Announcement>> getAnnouncements() {
    List<Announcement> announcements = announcementService.getAllAnnouncements();
    return Result.success(announcements);
  }

  /**
   * 分页获取公告
   */
  @GetMapping("/announcements/page")
  public Result<Map<String, Object>> getAnnouncementsByPage(
      @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
      @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
    List<Announcement> announcements = announcementService.getAnnouncementsByPage(pageNum, pageSize);

    Map<String, Object> data = new HashMap<>();
    data.put("list", announcements);
    data.put("pageNum", pageNum);
    data.put("pageSize", pageSize);

    return Result.success(data);
  }

  /**
   * 获取公告详情
   */
  @GetMapping("/announcements/{id}")
  public Result<Announcement> getAnnouncementDetail(@PathVariable("id") Integer id) {
    Announcement announcement = announcementService.getAnnouncementById(id);

    if (announcement == null) {
      throw new NotFoundException("公告不存在");
    }

    return Result.success(announcement);
  }

  /**
   * 添加公告（管理员）
   */
  @PostMapping("/admin/announcements")
  public Result<Announcement> addAnnouncement(@RequestBody Announcement announcement) {
    // 验证是否为管理员
    String userType = TokenUtil.getUserType();
    String userId = TokenUtil.getUserId();

    if (userType == null || userId == null) {
      throw new UnauthorizedException("请先登录");
    }

    if (!"admin".equals(userType)) {
      throw new UnauthorizedException("无权限进行此操作");
    }

    // 设置发布人信息
    announcement.setPublisherId(Integer.valueOf(userId));

    int result = announcementService.addAnnouncement(announcement);

    if (result <= 0) {
      throw new BusinessException(ResultCode.SYSTEM_ERROR, "添加公告失败");
    }

    return Result.success(announcement);
  }

  /**
   * 更新公告（管理员）
   */
  @PutMapping("/admin/announcements/{id}")
  public Result<Void> updateAnnouncement(
      @PathVariable("id") Integer id,
      @RequestBody Announcement announcement) {
    // 验证是否为管理员
    String userType = TokenUtil.getUserType();

    if (userType == null) {
      throw new UnauthorizedException("请先登录");
    }

    if (!"admin".equals(userType)) {
      throw new UnauthorizedException("无权限进行此操作");
    }

    // 设置公告ID
    announcement.setId(id);

    int result = announcementService.updateAnnouncement(announcement);

    if (result <= 0) {
      throw new BusinessException(ResultCode.SYSTEM_ERROR, "更新公告失败");
    }

    return Result.success();
  }

  /**
   * 删除公告（管理员）
   */
  @DeleteMapping("/admin/announcements/{id}")
  public Result<Void> deleteAnnouncement(@PathVariable("id") Integer id) {
    // 验证是否为管理员
    String userType = TokenUtil.getUserType();

    if (userType == null) {
      throw new UnauthorizedException("请先登录");
    }

    if (!"admin".equals(userType)) {
      throw new UnauthorizedException("无权限进行此操作");
    }

    int result = announcementService.deleteAnnouncement(id);

    if (result <= 0) {
      throw new BusinessException(ResultCode.SYSTEM_ERROR, "删除公告失败");
    }

    return Result.success();
  }
}